<template>
  <div class="company-container">
    <!-- 公司信息展示 -->
    <div class="company-info" v-if="companyInfo">
      <el-card class="company-card">
        <div class="company-header">
          <div class="company-logo">
            <el-image 
              :src="companyInfo.companyLogo" 
              fit="contain"
              :preview-src-list="[companyInfo.companyLogo]">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
          <div class="company-title">
            <div class="title-row">
              <h2>{{ companyInfo.companyName }}</h2>
              <el-button type="primary" v-if="userRole === 0" @click="openEditDialog">编辑公司信息</el-button>
            </div>
            <p class="company-desc">{{ companyInfo.companyDesc }}</p>
          </div>
        </div>

        <div class="company-details">
          <div class="detail-item">
            <span class="label">公司地址：</span>
            <span class="value">{{ companyInfo.companyAddress }}</span>
          </div>
          <div class="detail-item">
            <span class="label">公司图片：</span>
            <div class="company-images">
              <el-image 
                v-for="(image, index) in companyInfo.companyImage.split(',')" 
                :key="index"
                :src="image"
                fit="cover"
                :preview-src-list="companyInfo.companyImage.split(',')">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
          </div>
          <div class="detail-item">
            <span class="label">公司备注：</span>
            <span class="value">{{ companyInfo.remarks }}</span>
          </div>
          <div class="detail-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ companyInfo.creatTime ? companyInfo.creatTime.replace('T', ' ') : '' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">更新时间：</span>
            <span class="value">{{ companyInfo.updateTime ? companyInfo.updateTime.replace('T', ' ') : '' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">更新人：</span>
            <span class="value">{{ companyInfo.updateUserName }}</span>
          </div>
        </div>

        <div class="company-contacts">
          <h3>联系方式</h3>
          <el-table :data="companyInfo.companyContacts" style="width: 100%">
            <el-table-column prop="name" label="联系人" width="180"></el-table-column>
            <el-table-column prop="phone" label="联系电话" width="200"></el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 编辑公司信息对话框 -->
    <el-dialog title="编辑公司信息" :visible.sync="editDialogVisible" width="800px">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="120px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="editForm.companyName" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="公司地址" prop="companyAddress">
          <el-input v-model="editForm.companyAddress" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="公司简介" prop="companyDesc">
          <el-input type="textarea" v-model="editForm.companyDesc" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="公司LOGO" prop="companyLogo">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleLogoSuccess"
            :before-upload="beforeLogoUpload"
            :show-file-list="false">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">建议尺寸：200x200px，支持jpg/png格式</div>
          </el-upload>
          <el-image 
            v-if="editForm.companyLogo"
            :src="editForm.companyLogo"
            style="width: 100px; height: 100px; margin-top: 10px;">
          </el-image>
        </el-form-item>
        <el-form-item label="公司图片" prop="companyImage">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-remove="handleImageRemove"
            multiple
            list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
          <div slot="tip" class="el-upload__tip">建议尺寸：800x600px，支持jpg/png格式</div>
        </el-form-item>
        <el-form-item label="公司备注" prop="remarks">
          <el-input type="textarea" v-model="editForm.remarks" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <div v-for="(contact, index) in editForm.companyContact" :key="index" class="contact-item">
            <el-input v-model="contact.name" placeholder="联系人姓名" style="width: 200px; margin-right: 10px;"></el-input>
            <el-input v-model="contact.phone" placeholder="联系电话" style="width: 200px;"></el-input>
            <el-button type="danger" icon="el-icon-delete" circle @click="removeContact(index)"></el-button>
          </div>
          <el-button type="primary" icon="el-icon-plus" @click="addContact">添加联系方式</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Company',
  data() {
    return {
      userRole: null,
      companyInfo: null,
      editDialogVisible: false,
      editForm: {
        id: null,
        companyName: '',
        companyAddress: '',
        companyDesc: '',
        companyLogo: '',
        companyImage: '',
        remarks: '',
        companyContact: []
      },
      rules: {
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' }
        ],
        companyAddress: [
          { required: true, message: '请输入公司地址', trigger: 'blur' }
        ]
      },
      uploadUrl: 'http://localhost:8080/zsd-order/order-info/upWasteImage'
    };
  },
  mounted() {
    this.fetchCompanyInfo();
  },
  methods: {
    // 从token中获取用户角色
    getUserRoleFromToken() {
      try {
        const loginUser = JSON.parse(localStorage.getItem("loginUser"));
        console.log('loginUser:', loginUser);
        if (loginUser && loginUser.token) {
          const base64Url = loginUser.token.split('.')[1];
          const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
          const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
          }).join(''));

          const payload = JSON.parse(jsonPayload);
          console.log('Token payload:', payload);
          // 修改role的解析逻辑
          if (payload.role !== undefined && payload.role !== null) {
            this.userRole = Number(payload.role);
          } else {
            this.userRole = null;
          }
          console.log('Parsed userRole:', this.userRole);
        }
      } catch (error) {
        console.error('解析token失败:', error);
        this.userRole = null;
      }
    },
    // 获取公司信息
    fetchCompanyInfo() {
      this.$http.get('/zsd-merchant/company/list').then(response => {
        if (response.data.code === 200) {
          this.companyInfo = response.data.data;
        } else {
          this.$message.error(response.data.msg || '获取公司信息失败');
        }
      }).catch(error => {
        console.error('Error:', error);
        this.$message.error('获取公司信息失败');
      });
    },

    // 打开编辑对话框
    openEditDialog() {
      if (this.companyInfo) {
        this.editForm = {
          id: this.companyInfo.id,
          companyName: this.companyInfo.companyName,
          companyAddress: this.companyInfo.companyAddress,
          companyDesc: this.companyInfo.companyDesc,
          companyLogo: this.companyInfo.companyLogo,
          companyImage: this.companyInfo.companyImage,
          remarks: this.companyInfo.remarks,
          companyContact: this.companyInfo.companyContacts || []
        };
        this.editDialogVisible = true;
      }
    },

    // 提交编辑表单
    submitEditForm() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.$http.put('/zsd-merchant/company/update', this.editForm).then(response => {
            if (response.data.code === 200) {
              this.$message.success('更新公司信息成功');
              this.editDialogVisible = false;
              this.fetchCompanyInfo();
            } else {
              this.$message.error(response.data.msg || '更新公司信息失败');
            }
          }).catch(error => {
            console.error('Error:', error);
            this.$message.error('更新公司信息失败');
          });
        }
      });
    },

    // 处理LOGO上传成功
    handleLogoSuccess(response, file) {
      if (response.code === 200) {
        this.editForm.companyLogo = response.data;
        this.$message.success('LOGO上传成功');
      } else {
        this.$message.error(response.msg || 'LOGO上传失败');
      }
    },

    // 处理图片上传成功
    handleImageSuccess(response, file) {
      if (response.code === 200) {
        const images = this.editForm.companyImage ? this.editForm.companyImage.split(',') : [];
        images.push(response.data);
        this.editForm.companyImage = images.join(',');
        this.$message.success('图片上传成功');
      } else {
        this.$message.error(response.msg || '图片上传失败');
      }
    },

    // 处理图片移除
    handleImageRemove(file, fileList) {
      const images = this.editForm.companyImage.split(',');
      const index = images.indexOf(file.response.data);
      if (index > -1) {
        images.splice(index, 1);
        this.editForm.companyImage = images.join(',');
      }
    },

    // 上传前检查
    beforeLogoUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传LOGO只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传LOGO大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },

    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isImage && isLt5M;
    },

    // 添加联系方式
    addContact() {
      this.editForm.companyContact.push({
        name: '',
        phone: ''
      });
    },

    // 移除联系方式
    removeContact(index) {
      this.editForm.companyContact.splice(index, 1);
    }
  },
  created() {
    // 从token中获取用户角色
    this.getUserRoleFromToken();
  }
};
</script>

<style scoped>
.company-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.company-card {
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.company-header {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.company-logo {
  width: 100px;
  height: 100px;
  margin-right: 20px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f7fa;
}

.company-title {
  flex: 1;
}

.title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.title-row h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.company-desc {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.company-details {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.label {
  width: 100px;
  color: #606266;
  font-weight: bold;
}

.value {
  flex: 1;
  color: #303133;
}

.company-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.company-images .el-image {
  width: 150px;
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
}

.company-contacts {
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

.company-contacts h3 {
  margin: 0 0 15px 0;
  font-size: 18px;
  color: #303133;
}

.contact-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.form-input {
  width: 400px !important;
}

.upload-demo {
  margin-bottom: 10px;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.el-dialog {
  margin-top: 5vh !important;
  border-radius: 8px;
}

.el-dialog__body {
  padding: 30px 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-form-item__label {
  font-weight: bold;
}
</style>